package com.irate.dao;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.http.AsyncHttpClient;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.http.RequestParams;
import com.irate.model.User;
import com.irate.provider.Constant;
import com.irate.provider.ContentManager;
import com.irate.service.AsyncHTTPRest;

public class UserDAO {

	public void parsedata(String json) {

		try {
			JSONObject obj = new JSONObject(json);
			JSONObject friendObj;
			try {
				friendObj = (JSONObject) obj.getJSONArray("message").get(0);
			} catch (Exception e) {
				friendObj = (JSONObject) obj.getJSONObject("message");

			}

			User user = new User();
			user.setId(friendObj.getString("user_id"));
			user.setEmail(friendObj.getString("user_name"));
			user.setSex(friendObj.getString("user_gender"));
			user.setFirst_name(friendObj.getString("user_firstname"));
			user.setLast_name(friendObj.getString("user_lastname"));
			user.setAge(friendObj.getString("age_group_id"));
			user.setRegion(friendObj.getString("region_id"));
			user.setAvatar(friendObj.getString("user_photo"));

			try {
				JSONObject objSetting = new JSONObject(
						friendObj.getString("user_setting"));
				user.setUser_setting(objSetting.getString("privacy"));
			} catch (Exception e) {

			}

			try {
				user.setUser_facebook_id(friendObj
						.getString("user_facebook_id"));
			} catch (Exception e) {

			}

			ContentManager.getInstance().setCurrentUser(user);
			ContentManager.getInstance().isLogin(true);

		} catch (Exception e) {

		}
	}

	public List<User> parseListData(String json) {
		List<User> lstData = new ArrayList<User>();
		try {
			JSONObject obj = new JSONObject(json);
			JSONArray friendArray = (JSONArray) obj.getJSONArray("message");

			for (int i = 0; i < friendArray.length(); i++) {
				JSONObject friendObj = friendArray.getJSONObject(i);

				User user = new User();
				user.setId(friendObj.getString("user_id"));
				user.setEmail(friendObj.getString("user_name"));
				user.setSex(friendObj.getString("user_gender"));
				user.setFirst_name(friendObj.getString("user_firstname"));
				user.setLast_name(friendObj.getString("user_lastname"));
				try {
					user.setAge(friendObj.getString("age_group_id"));
				} catch (Exception e) {

				}
				user.setRegion(friendObj.getString("region_id"));
				try {
					user.setAvatar(friendObj.getString("user_photo"));
				} catch (Exception e) {

				}

				lstData.add(user);
			}

		} catch (Exception e) {

		}
		return lstData;
	}

	public void login(String username, String password,
			AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_LOGIN;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			RequestParams param = new RequestParams();
			param.put("username", username);
			param.put("password", password);

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void loginWithFacebook(String access_token,
			AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {
			if (dialog != null)
				dialog.dismiss();
			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_FB_LOGIN;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			RequestParams param = new RequestParams();
			param.put("token_access", access_token);

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void register(User user, String password,
			AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {
			if (dialog != null)
				dialog.dismiss();
			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_REGISTER;

			RequestParams param = new RequestParams();
			param.put("username", user.getEmail().trim());
			param.put("password", password);
			param.put("gender", user.getSex());
			param.put("first_name", user.getFirst_name().trim());
			param.put("last_name", user.getLast_name().trim());
			param.put("age", user.getAge());
			param.put("region", user.getRegion());

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void upLoadPhoto(String path, Context context, ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_UPLOAD;

			new FileUpload().execute(link, path, context, dialog);
		}
	}

	class FileUpload extends AsyncTask<Object, Void, String> {

		private Context context;
		private ProgressDialog dialog;

		@Override
		protected String doInBackground(Object... params) {

			context = (Context) params[2];
			dialog = (ProgressDialog) params[3];

			String result = "";
			try {
				AsyncHttpClient asynHttpClient = AsyncHTTPRest
						.getAsynHttpClient();
				HttpClient httpClient = asynHttpClient.getHttpClient();

				HttpPost post = new HttpPost(new URI(params[0].toString()));
				File file = new File(params[1].toString());

				String extension = "";

				int i = file.getName().lastIndexOf('.');
				if (i > 0) {
					extension = file.getName().substring(i + 1);
				}

				String mime_type = "";
				mime_type = MimeTypeMap.getSingleton()
						.getMimeTypeFromExtension(extension);

				HttpEntity httpEntity = MultipartEntityBuilder
						.create()
						.addBinaryBody("fileUpload", file,
								ContentType.create(mime_type), file.getName())
						.build();

				post.setEntity(httpEntity);
				post.addHeader("X-API-KEY", "12345-67890");

				HttpResponse response = httpClient.execute(post);
				result = EntityUtils.toString(response.getEntity());
				dialog.dismiss();

			} catch (Exception e) {
				e.printStackTrace();
				String str = e.toString();
				System.out.print(str);
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			try {
				JSONObject obj = new JSONObject(result);
				
				if (obj.getString("return").toString().equals("true")) {
					ContentManager.getInstance().getCurrentUser().setAvatar(obj.getString("message"));
					Toast.makeText(context, "Upload success",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(context,
							obj.getString("message").toString(),
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

			}

		}

	}

	public void getFriendList(AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_FRIEND
					+ "/" + Constant.SERVICE_FRIEND_LIST;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, null, handler);
		}
	}

	public void logout(AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_LOGOUT;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			clearSession();

			AsyncHTTPRest.post(link, headers, null, handler);
		}
	}

	public void searchFriend(String email, AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_FRIEND
					+ "/" + Constant.SERVICE_SEARCH_FRIEND;

			RequestParams param = new RequestParams();
			param.put("username", email);

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void updateMySelf(User user, AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_UPDATE;

			RequestParams param = new RequestParams();
			param.put("gender", user.getSex());
			param.put("first_name", user.getFirst_name().trim());
			param.put("last_name", user.getLast_name().trim());
			param.put("age", user.getAge());
			param.put("region", user.getRegion());

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void changePassWord(String oldPass, String newPass,
			AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_CHANGE_PASSWORD;

			RequestParams param = new RequestParams();
			param.put("old_pass", oldPass);
			param.put("new_pass", newPass);

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void getRecommendList(AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_FRIEND
					+ "/" + Constant.SERVICE_FRIEND_RECOMEND;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, null, handler);
		}
	}

	public void removeFriend(String friendID, AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_FRIEND
					+ "/" + Constant.SERVICE_FRIEND_REMOVE;

			RequestParams param = new RequestParams();
			param.put("friend_id", friendID);

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void submitPrivateSettingToServer(int index,
			AsyncHttpResponseHandler handler, Context context,
			ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_FRIEND_SET_SETTING;

			RequestParams param = new RequestParams();
			param.put("privacy", index + "");

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void inviteFriend(String email, AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_FRIEND
					+ "/" + Constant.SERVICE_FRIEND_SET_INVITATION;

			RequestParams param = new RequestParams();
			param.put("email", email);

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}
	
	public void forgorPass(String email, AsyncHttpResponseHandler handler,
			Context context, ProgressDialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_CATEGORY_USER
					+ "/" + Constant.SERVICE_FORGOT_PASS;

			RequestParams param = new RequestParams();
			param.put("email", email);

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, param, handler);
		}
	}

	public void clearSession() {
		ContentManager.getInstance().getListFriend().clear();
		ContentManager.getInstance().setCurrentUser(new User());
		ContentManager.getInstance().setCurrentFriendLayoutSelected(0);
		ContentManager.getInstance().setStrSearchFriendAddFriend("");
	}
}
